package com.example.pageradapterdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.util.Log;

import com.example.pageradapterdemo.fragment.MyFragment;
import com.example.pageradapterdemo.fragment.Page0Fragment;
import com.example.pageradapterdemo.fragment.Page1Fragment;
import com.example.pageradapterdemo.fragment.Page2Fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ViewPagerDemo3Activity extends AppCompatActivity {
    private MyFragmentPagerAdapter fragmentPagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager_demo3);
        final ViewPager viewPager = findViewById(R.id.viewPager1);
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new Page0Fragment());
        fragments.add(new Page1Fragment());
        fragments.add(new Page2Fragment());
        fragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fragments);
        viewPager.setAdapter(fragmentPagerAdapter);
    }

    public class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
        private List<Fragment> fragments;

        public MyFragmentPagerAdapter(@NonNull FragmentManager fm, List<Fragment> fragments) {
            super(fm,FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
            this.fragments = fragments;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            Log.e("position","getItemPosition(" + object.getClass().getName() + ")");
            if (object instanceof Page0Fragment) {
                ((Page0Fragment) object).updateDate(new Date());
            }else if(object instanceof Page1Fragment){
                ((Page1Fragment) object).updateContent("你好");
            }else if(object instanceof Page2Fragment){
                ((Page2Fragment) object).updateCheckedStatus(true);
            }
            return super.getItemPosition(object);
        }
    }

}